<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>车辆管理</el-breadcrumb-item>
      <el-breadcrumb-item>车辆列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入要查询的车辆号：格式如：豫A 666"
            v-model="queryInfo.query"
            clearable
            @change="getCarsList"
            @clear="getCarsList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getCarsList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
            v-if="getuserInfo.role == '管理员'"
            >添加车辆</el-button
          >
        </el-col>
      </el-row>

      <!-- 车辆信息列表区域 -->
      <el-table :data="carslist" bcar stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="车牌号" prop="car_card"></el-table-column>
        <el-table-column label="联系人" prop="car_username"></el-table-column>
        <el-table-column label="手机" prop="car_phone"></el-table-column>
        <el-table-column
          label="车辆最近使用日期"
          prop="car_date"
        ></el-table-column>
        <el-table-column label="车辆类型" prop="car_style"></el-table-column>
        <el-table-column
          label="运输方式"
          prop="car_transport"
        ></el-table-column>
        <!-- <el-table-column label="车辆地址" prop="car_address"></el-table-column> -->
        <!-- <el-table-column label="车辆方式" prop="car_style"></el-table-column> -->
        <el-table-column
          label="车辆状态"
          prop="car_status"
          :filters="[
            { text: '空闲', value: '空闲' },
            { text: '忙碌', value: '忙碌' },
          ]"
          :filter-method="filterTag"
          filter-placement="bottom-end"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.car_status === '空闲' ? 'primary' : 'success'"
              disable-transitions
              >{{ scope.row.car_status }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180px"
          v-if="getuserInfo.role == '管理员'"
        >
          <template slot-scope="scope">
            <!-- {{ scope.row.id }}  -->
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.car_id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.car_id)"
            ></el-button>
            <!-- 修改车辆状态按钮 -->
            <!-- <el-tooltip
              effect="dark"
              content="修改车辆运输状态"
              placement="top"
              :enterable="false"
              v-if="scope.row.car_status == '空闲'"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setStatus(scope.row)"
              ></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加车辆的对话框 -->
    <el-dialog
      title="添加车辆"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="140px"
      >
        <el-form-item label="车牌号" prop="car_card">
          <el-input v-model="addForm.car_card"></el-input>
          <span>例如： 豫A 666</span>
        </el-form-item>
        <el-form-item label="车辆联系人" prop="car_username">
          <el-input v-model="addForm.car_username"></el-input>
        </el-form-item>
        <el-form-item label="联系人电话" prop="car_phone">
          <el-input v-model="addForm.car_phone"></el-input>
        </el-form-item>
        <el-form-item label="车辆最近使用日期" prop="car_date">
          <!-- <el-input v-model="addForm.car_date"></el-input> -->
          <el-date-picker
            v-model="addForm.car_date"
            type="datetime"
            placeholder="选择日期时间"
            format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="车辆类型" prop="car_style">
          <!-- <el-input v-model="addForm.car_style"></el-input> -->
          <el-select v-model="addForm.car_style" placeholder="请选择">
            <el-option
              v-for="item in carStyle"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运输方式" prop="car_transport">
          <el-input v-model="addForm.car_transport"></el-input>
        </el-form-item>

        <el-form-item label="车辆状态" prop="car_status">
          <!-- <el-input v-model="addForm.car_status"></el-input> -->
          <el-select v-model="addForm.car_status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addcar">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改车辆信息的对话框 -->
    <el-dialog
      title="修改车辆信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="130px"
      >
        <el-form-item label="车牌号" prop="car_card">
          <el-input v-model="editForm.car_card"></el-input>
        </el-form-item>
        <el-form-item label="车辆联系人" prop="car_username">
          <el-input v-model="editForm.car_username"></el-input>
        </el-form-item>
        <el-form-item label="联系人电话" prop="car_phone">
          <el-input v-model="editForm.car_phone"></el-input>
        </el-form-item>
        <el-form-item label="车辆最近使用日期" prop="car_date">
          <!-- <el-input v-model="editForm.car_date"></el-input> -->
          <el-date-picker
            v-model="editForm.car_date"
            type="datetime"
            placeholder="选择日期时间"
            format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="车辆类型" prop="car_style">
          <el-input v-model="editForm.car_style"></el-input>
        </el-form-item>
        <el-form-item label="运输方式" prop="car_transport">
          <el-input v-model="editForm.car_transport"></el-input>
        </el-form-item>

        <el-form-item label="车辆状态" prop="car_status">
          <!-- <el-input v-model="editForm.car_status"></el-input> -->
          <el-select v-model="editForm.car_status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editcarInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Cars',
  data() {
    // 自定义验证手机号的规则
    var checkphone = (rules, value, cb) => {
      // 验证手机号的正则表达式
      const regphone = /^1[3|4|5|7|8][0-9]{9}$/

      if (regphone.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // searchTxt: '',
      // searchValue: '',
      tableData: [],
      token: '',
      // -----------------
      // 获取车辆信息列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 10,
      },
      carslist: [],
      total: 0,
      // 控制添加车辆对话框的显示与隐藏
      addDialogVisible: false,
      // 添加车辆的表单数据
      addForm: {
        car_card: '',
        car_style: '',
        car_date: '',
        car_transport: '',
        car_username: '',
        car_phone: '',
        // car_address: '',
        car_style: '',
        car_status: '',
      },
      // 添加表单的验证规则对象
      addFormRules: {
        car_card: [
          { required: true, message: '请输入车辆号', trigger: 'blur' },
        ],
        car_style: [
          { required: true, message: '请输入车辆名', trigger: 'blur' },
        ],
        car_date: [{ required: true, message: '请输入日期', trigger: 'blur' }],
        car_transport: [
          { required: true, message: '请输入车辆数量', trigger: 'blur' },
          {
            min: 1,
            // max: 15,
            message: '数量必须大于 1',
            trigger: 'change',
          },
        ],
        car_username: [
          { required: true, message: '请输入车辆信息名', trigger: 'blur' },
          // { validator: checkEmail, trigger: 'blur' },
        ],
        car_phone: [
          { required: true, message: '请输入手机', trigger: 'change' },
          { validator: checkphone, trigger: 'change' },
        ],
        // car_address: [
        //   { required: true, message: '请输入车辆地址', trigger: 'blur' },
        // ],
        car_style: [
          { required: true, message: '请输入车辆类型', trigger: 'blur' },
        ],
        car_status: [
          {
            required: true,
            // type: Number,
            message: '请选择车辆状态，0代表空闲，1代表空闲',
            trigger: 'change',
          },
        ],
      },
      // 车辆状态选择
      options: [
        {
          value: '0',
          label: '空闲',
        },
        {
          value: '1',
          label: '忙碌',
        },
      ],
      // 车辆类型选择
      carStyle: [
        {
          value: '普通',
          label: '普通',
        },
        {
          value: '重型货车',
          label: '重型货车',
        },
        {
          value: '中型货车',
          label: '中型货车',
        },
        {
          value: '轻型货车',
          label: '轻型货车',
        },
        {
          value: '微型货车',
          label: '微型货车',
        },
      ],
      // 控制修改车辆信息对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的车辆信息信息对象
      editForm: {},
      // 修改表单的 验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入车辆信息邮箱', trigger: 'blur' },
          // { validator: checkEmail, trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入车辆信息手机号', trigger: 'blur' },
          { validator: checkphone, trigger: 'blur' },
        ],
      },
      // 控制分配角色对话框的显示与隐藏
      setStatusDialogVisible: false,
      // 需要被分配角色（那一行）的车辆信息信息
      userInfo: {},
      // 所有角色的数据列表
      statusList: [],
      // 已选中的角色id值
      selectedRoled: '',
    }
  },
  created() {
    this.getCarsList()
    console.log(this.getuserInfo, '111111111111')
  },
  computed: {
    getuserInfo() {
      return this.$store.state.userInfo
    },
  },
  methods: {
    // 获取所有车辆信息信息
    getCarsList() {
      this.$http
        .get('/myApi/car/carinfoAll', {
          params: this.queryInfo,
        })
        .then((res) => {
          console.log(res.data, '00000000000')
          if (res.data.code == 200) {
            res.data.data.filter((item) => {
              item.car_date = item.car_date.split('').splice(0, 10).join('')
              item.car_status = item.car_status == 0 ? '空闲' : '忙碌'
            })
            this.carslist = res.data.data
            this.total = res.data.total
          }
        })
    },
    // 修改对话框
    async showEditDialog(id) {
      // 根据传进来的id 发起 axios请求，得到对车辆信息的信息
      const { data: res } = await this.$http.get('/myApi/car/carinfo/' + id)
      console.log(res, '???????')
      if (res.code !== 200) {
        return this.$message.error('查询车辆信息信息失败')
      }
      this.$message.success('查询车辆信息信息成功')
      // 请求成功后将车辆信息的信息保存到 data中
      this.editForm = res.data
      this.editForm.car_status = this.editForm.car_status == 0 ? '空闲' : '忙碌'
      // this.selectedRoled = this.editForm.role
      // 在展示对话框之前， 获取所有的角色的列表
      // const { data: res1 } = await this.$http.get('/myApi/car/status')

      // if (res1.code !== 200) {
      //   return this.$message.error('获取车辆状态列表失败！')
      // }
      // console.log(res1.data, 'status stauts')
      // this.statusList = res1.data

      this.editDialogVisible = true
      // console.log(id)
    },
    // 监听修改车辆信息对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改车辆信息信息并提交
    editcarInfo() {
      // validate()是提交前 对整个表单进行校验的方法
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return
        console.log(this.editForm.car_status, 'zzzzzzzzzzzzzzzzzz')
        // this.editForm.car_status =
        //   this.editForm.car_status == '空闲' ? 0 : 1
        // 可以发起修改车辆信息的网络请求
        const { data: res } = await this.$http.post(
          '/myApi/car/carinfo/' + this.editForm.car_id,
          this.editForm
        )
        console.log(res)
        if (res.code !== 200) {
          return this.$message.error('更新车辆信息信息失败')
        }
        // 隐藏修改车辆信息的对话框
        this.editDialogVisible = false
        // 重新渲染数据
        this.getCarsList()
        // 提示修改成功
        this.$message.success('更新车辆信息信息成功')
      })
    },
    // 根据id 删除对应的车辆信息信息
    async removeUserById(id) {
      // 弹框询问车辆信息是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该车辆信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err) // cancel
      // 如果车辆信息点击确认 删除，则返回值为 字符串 confirm
      // 如果车辆信息点击取消 删除，则返回值为 字符串 cancel
      // console.log(confirmResult) // Promise对象
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除!')
      }
      // console.log('确认了删除')
      const { data: res } = await this.$http.delete('/myApi/car/carinfo/' + id)

      if (res.code !== 200) {
        return this.$message.error('删除车辆信息信息失败!')
      }
      this.$message.success('删除车辆信息信息成功')
      // 重新渲染列表
      this.getCarsList()
    },
    // 展示分配角色的对话框
    async setStatus(userInfo) {
      this.userInfo = userInfo
      // 在展示对话框之前， 获取所有的角色的列表
      const { data: res } = await this.$http.get('/myApi/car/roles')

      if (res.code !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      console.log(res.data, 'role  role')
      this.statusList = res.data

      this.setStatusDialogVisible = true
    },
    // 点击 分配角色对话框的‘确认’ 按钮
    async saveRoleInfo() {
      if (!this.selectedRoled) {
        return this.$message.error('请选择要分配的角色！')
      }

      const { data: res } = await this.$http.get(
        `/myApi/car/userinfoRole/${this.userInfo.id}`,
        {
          params: { role: this.selectedRoled },
        }
      )
      if (res.code !== 200) {
        return this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色成功')
      // 重新渲染列表数据
      this.getCarsList()
      // 隐藏对话框
      this.setStatusDialogVisible = false
    },
    // 监听分配角色对话框的关闭事件
    setStatusDialogClosed() {
      this.selectedRoled = ''
      this.userInfo = {}
    },
    // 监听添加车辆对话框的关闭事件
    addDialogClosed() {
      // 拿到对话框的引用，调用自身的resetFields方法，重置表单
      this.$refs.addFormRef.resetFields()
    },
    // 添加车辆信息
    addcar() {
      this.$refs['addFormRef'].validate((valid) => {
        // 校验失败
        if (!valid) return console.log('添加车辆信息失败!!')
        console.log(this.addForm.car_date)
        // this.addForm.car_date = this.addForm.car_date
        //   .split('')
        //   .splice(0, 10)
        //   .join('')
        // 添加车辆信息
        this.$http.post('/myApi/car/addcarinfo', this.addForm).then((res) => {
          console.log(res.data)
          if (res.data.code !== 200) {
            this.$message.warning('添加失败，车辆信息名或密码错误')
          } else {
            this.$message.success('添加车辆成功')
            // 隐藏添加车辆的对话框
            this.addDialogVisible = false
            this.getCarsList()
          }
        })
      })
    },
    // 分页=========
    // 监听pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      console.log(this.queryInfo.pagesize, 'pagesize')
      this.getCarsList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      console.log(this.queryInfo.pagenum, 'pagenum')
      this.getCarsList()
    },
    // 监听 switch 开关状态的变化
    async userStateChanged(userinfo) {
      // console.log(userinfo)
      // const { data: res } = await this.$http.put(
      //   `users/${userinfo.id}/state/${userinfo.mg_state}`
      // )
      // if (res.meta.status !== 200) {
      //   userinfo.mg_state = !userinfo.mg_state
      //   return this.$message.error('更新车辆信息状态失败')
      // }
      this.$message.success('更新车辆信息状态成功')
    },
    filterTag(value, row) {
      return row.car_status === value
    },
  },
}
</script>

<style lang="less" scoped>
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>
